package com.nageoffer.aicloud.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nageoffer.aicloud.common.convention.exception.ClientException;
import com.nageoffer.aicloud.dao.entity.UserDO;
import com.nageoffer.aicloud.dao.mapper.UserMapper;
import com.nageoffer.aicloud.dto.req.UserLoginReqDTO;
import com.nageoffer.aicloud.dto.req.UserRegisterReqDTO;
import com.nageoffer.aicloud.dto.resp.UserLoginRespDTO;
import com.nageoffer.aicloud.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static com.nageoffer.aicloud.common.content.RedisKeyContent.CAPTCHA_KEY;
import static com.nageoffer.aicloud.common.enums.UserErrorCode.USER_EXISTS;

/**
 * 用户接口实现层
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {
    private final StringRedisTemplate stringRedisTemplate;

    private final PasswordEncoder passwordEncoder;

    @Value("${jwt.secret}")
    private String jwtSecret;

    @Override
    public UserLoginRespDTO userLogin(UserLoginReqDTO requestParam, HttpServletRequest request) {
        if (StrUtil.isNotBlank(requestParam.getCaptcha())) {
            String captcha = stringRedisTemplate.opsForValue().get(CAPTCHA_KEY +
                    "Captcha-" + SecureUtil.md5(request.getRemoteAddr()));
            if (!captcha.equalsIgnoreCase(requestParam.getCaptcha())) {
                stringRedisTemplate.delete(CAPTCHA_KEY +
                        "Captcha-" + SecureUtil.md5(request.getRemoteAddr()));
                throw new ClientException("用户验证码输入错误!");
            }
        }
        stringRedisTemplate.delete(CAPTCHA_KEY +
                "Captcha-" + SecureUtil.md5(request.getRemoteAddr()));
        // 判断用户名密码是否正确
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername())
                .eq(UserDO::getDelFlag, 0);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if (Objects.isNull(userDO)) {
            throw new ClientException("当前无该用户信息!");
        }
        if (!passwordEncoder.matches(requestParam.getPassword(), userDO.getPassword())) {
            throw new ClientException("用户名/密码出错!");
        }
        // 通过JWT生成 token返回
        Map<String, Object> playLoad = new HashMap<>();
        playLoad.put("id", userDO.getId());
        playLoad.put("username", userDO.getUsername());
        playLoad.put("exp", System.currentTimeMillis() + 1000 * 60 * 60 * 24);
        return UserLoginRespDTO.builder()
                .token(JWTUtil.createToken(playLoad, jwtSecret.getBytes()))
                .username(userDO.getUsername())
                .build();
    }

    @Override
    public void userRegister(UserRegisterReqDTO requestParam) {
        try {
            requestParam.setPassword(passwordEncoder.encode(requestParam.getPassword()));
            baseMapper.insert(BeanUtil.toBean(requestParam, UserDO.class));
        } catch (Throwable ex) {
            throw new ClientException(USER_EXISTS);
        }
    }
}
